package com.linglingC.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.linglingC.pojo.Result;
import com.linglingC.pojo.User;
import com.linglingC.service.UserService;
import com.linglingC.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override //true放行false不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String s=request.getRequestURI().toString();

        log.info("请求url:{}",s);

        String jwt=request.getHeader("token");

        if(!StringUtils.hasLength(jwt)){
            log.info("请求头token为空,返回未登录的信息");
            Result error=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);

            return false;
        }

        try{
            Map<String,Object> claims= (Map<String,Object>)JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败,返回登录错误信息");
            Result error=Result.error("NOT_LOGIN");

            String notLogin= JSONObject.toJSONString(error);

            response.getWriter().write(notLogin);

            return false;
        }



        log.info("令牌合法,放行");
        return true;
    }

}
